const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const pager = require("./util/PagerHelper.js");
const loginRoute = require("./routes/LoginRoute");
const usersRoute = require("./routes/UsersRoute");
const productsRoute = require("./routes/ProductsRoute");
const ordersRoute = require("./routes/OrdersRoute");
const adminsRoute = require("./routes/AdminsRoute");
const categoryRoute = require("./routes/CategoryRoute");
const commentRoute = require("./routes/CommentRoute");
const shoppingcartRoute = require("./routes/ShoppingcartRoute");
const rattingsRoute = require("./routes/RattingsRoute");
const menusRoute = require("./routes/MenusRoute");
const checkRoute = require("./routes/CheckRoute");
const addressRoute = require("./routes/AddressRoute");
// 1. 导入用于生成 JWT 字符串的包
const jwt = require("jsonwebtoken");
// 2. 导入用于将客户端发送过来的 JWT 字符串，解析还原成 JSON 对象的包
const expressJWT = require("express-jwt");
// 3. secret 一个密钥字符串
const secretKey = "stu-manager key";
app.locals.jwt = jwt;
app.locals.expressJWT = expressJWT;
app.locals.secretKey = secretKey;
//静态资源
app.use(express.static(__dirname));
//post请求参数中间件
/*
    extended
        true：qs库
        false：使用querystring库
 */
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json()); //vue中的axios发送的是json格式的数据
app.use(cookieParser("stumshop"));
//中间件，统一处理打印及分页插件，必须写在路由之前
app.use((req, res, next) => {
  console.log("req.url:", req.url);
  console.log("req.body:", req.body);
  let { pageNum, pageSize } = req.body;
  if (pageNum) {
    pager.pageNum = parseInt(pageNum);
  }
  if (pageSize) {
    pager.pageSize = parseInt(pageSize);
  }

  next();
});

//请求白名单，有的路由请求可以不需要带token验证
app.use(
  expressJWT({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: [
      "/api/login.do",
      "/api/logout.do",
      /^\/public\/.*/,
      "/api/users/register.do",
      "/",
      '/api/products/list.do',
      '/api/category/list.do',
      '/api/comment/list.do',
      '/api/users/publiclist.do'
    ],
  })
);

//路由，必须在bodyParser后面
app.use("/api", loginRoute);
app.use("/api/users", usersRoute);
app.use("/api/products", productsRoute);
app.use("/api/orders", ordersRoute);
app.use("/api/admins", adminsRoute);
app.use("/api/category", categoryRoute);
app.use("/api/comment", commentRoute);
app.use("/api/shoppingcart", shoppingcartRoute);
app.use("/api/rattings", rattingsRoute);
app.use("/api/menus", menusRoute);
app.use("/api/check", checkRoute);
app.use("/api/address", addressRoute);

app.use(function (err, req, res, next) {
  console.error("错误信息：", err);
  // res.json(err);
  if (err.message === 'jwt expired') {
    return res.send(res.json({
      code:402,
      msg:'token过期'
    }))
  }
  else if (err.name === 'UnauthorizedError') {
    return res.send(res.json({
      code:401,
      msg:'没有token'
    }))
  }else{
    res.json({
      code: 409,
      data: err,
    });
  }
  
});

const port = 8081;
//启动服务，监听端口号
app.listen(port, () => console.log(`服务启动成功，http://localhost:${port}`));

module.exports = app;
